package test01.Service;



import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import test01.redis.KeyPrefix;

import java.util.concurrent.TimeUnit;

/**
 * redis操作Service的实现类
 * Created by macro on 2018/8/7.
 */
@Service
public class RedisService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    public void set(String key, String value) {
        stringRedisTemplate.opsForValue().set(key, value);
    }


    public String get(String key) {
        return stringRedisTemplate.opsForValue().get(key);
    }


    public boolean expire(String key, long expire) {
        return stringRedisTemplate.expire(key, expire, TimeUnit.SECONDS);
    }


    public void remove(String key) {
        stringRedisTemplate.delete(key);
    }


    public Long increment(String key, long delta) {
        return stringRedisTemplate.opsForValue().increment(key,delta);
    }

    public boolean hasKey(String key) {
        return stringRedisTemplate.hasKey( key);
    }

    public void set(KeyPrefix keyPrefix, String key, String value) {
        if (keyPrefix.getExpireSeconds()<=0){
            stringRedisTemplate.opsForValue().set(keyPrefix.getPrefix()+key, value);
        }else {
            stringRedisTemplate.opsForValue().set(keyPrefix.getPrefix()+key, value,keyPrefix.getExpireSeconds(),TimeUnit.SECONDS);
        }
    }
    public String get(KeyPrefix keyPrefix,String key) {
        return stringRedisTemplate.opsForValue().get(keyPrefix.getPrefix()+key);
    }

}
